package com.example.springfeature.classloader;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

/**
 * Created with IDEA
 *
 * @author: 董文辉
 * Date: 2019/3/1
 * Time: 12:11
 */
public class MyClassLoader extends ClassLoader {
    private static final String BASE_CLASS_FOLDER = "C:\\Users\\13815\\Desktop\\学习相关\\springfeature\\customerclass\\";
    private static final String CLASS_SUFFIX = ".class";
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        //获取字节码文件
        File classFile = findClassFile(name);
        //读取字节码文件到字节流中
        byte[] classBytes = new byte[0];
        try {
            classBytes = readByteFromClassFile(classFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将字节流转换为class对象
        Class<?> aClass = this.defineClass(name, classBytes, 0, classBytes.length);
        return aClass;
    }

    private byte[] readByteFromClassFile(File classFile) throws Exception {
        FileInputStream fileInputStream = new FileInputStream(classFile);
        FileChannel inChannel = fileInputStream.getChannel();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        WritableByteChannel outChannel = Channels.newChannel(outputStream);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while(true){
            try {
                int i = inChannel.read(buffer);
                if(i <= 0 ){
                    break;
                }
                buffer.flip();
                outChannel.write(buffer);
                buffer.clear();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        fileInputStream.close();
        return outputStream.toByteArray();
    }

    private File findClassFile(String name) {
        String fileUrl = BASE_CLASS_FOLDER + name+ CLASS_SUFFIX;
        File file = new File(fileUrl);
        return file;
    }
}
